package com.tensquare.friend.controller;

import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.service.FriendService;
import com.tensquare.friend.service.NoFriendService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zzb
 * @version 1.0
 * @create 2020/12/24 10:25
 */
@RestController
@RequestMapping("friend")
public class FriendController {
    @Autowired
    private FriendService friendService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserClient userClient;
    @Autowired
    private NoFriendService noFriendService;
    //添加好友
    @PutMapping("like/{friendid}/{type}")
    public Result like(@PathVariable String friendid,@PathVariable Integer type) {
        Claims claims = (Claims) request.getAttribute("claims");
        if (claims != null) {
            //根据类型判断是否添加好友
            if (type == 1){
                //添加好友
                int count = friendService.addFriend(claims.getId(),friendid);
                //①更新粉丝数与关注数
                userClient.incFollow(claims.getId(),1);
                //②增加对方的粉丝数
                userClient.incFans(friendid,1);
                if (count == 0){
                    return new Result(false, StatusCode.REPERROR,"重复添加好友！");
                }
            }else if(type == 2){
                noFriendService.addNoFriend(claims.getId(),friendid);
            }
        }
        return new Result(true,StatusCode.OK,"添加好友成功");
    }

    //删除好友
    @DeleteMapping("{friendid}")
    public Result deleteFriend(@PathVariable String friendid){
        //得到当前登录用户id
        Claims claims = (Claims) request.getAttribute("claims");
        //判断是否为空
        if (claims != null){
            String userId = claims.getId();//当前登录用户id
            //删除好友
            friendService.delete(userId,friendid);
            //减少自己关注数
            userClient.incFollow(claims.getId(),-1);
            //减少对方的粉丝数
            userClient.incFans(friendid,-1);
            return new Result(true,StatusCode.OK,"删除好友成功");
        }else {
            System.out.println("claims = " + claims);
            return new Result(false,StatusCode.ACCESSERROR,"无权删除用户");
        }

    }
}
